<template>
  <view class="inspection-page">
    <!-- 导航栏 -->
    <view class="navbar">
      <image 
        class="icon-image" 
        src="/static/icons/arrow-left.svg" 
        mode="aspectFit" 
        @click="goBack"
      />
      <text class="navbar-title">巡检管理</text>
      <view class="navbar-right"></view>
    </view>

    <!-- 统计数据区域 -->
    <view class="stats-section">
      <view class="stats-grid">
        <view class="stat-item">
          <text class="stat-value">{{ statsData.totalBerths }}</text>
          <text class="stat-label">总泊位数</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{ statsData.availableBerths }}</text>
          <text class="stat-label">空余数</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{ statsData.disabledBerths }}</text>
          <text class="stat-label">禁用数</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{ statsData.registeredOrders }}</text>
          <text class="stat-label">已登记订单</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{ statsData.unregisteredOrders }}</text>
          <text class="stat-label">未登记订单</text>
        </view>
        <view class="stat-item">
          <text class="stat-value">{{ statsData.manualOrders }}</text>
          <text class="stat-label">人工取证订单</text>
        </view>
      </view>
    </view>

    <!-- 筛选区域 -->
    <view class="filter-section">
      <view class="filter-row">
        <view class="filter-item">
          <text class="filter-label">区域:</text>
          <picker 
            :value="selectedAreaIndex" 
            :range="areaList" 
            range-key="name"
            @change="onAreaChange"
          >
            <view class="picker-display">
              <text>{{ selectedArea.name || '请选择区域' }}</text>
              <image class="icon-image-small" src="/static/icons/chevron-down.svg" mode="aspectFit" />
            </view>
          </picker>
        </view>
        
        <view class="filter-item">
          <text class="filter-label">停车场:</text>
          <picker 
            :value="selectedParkingIndex" 
            :range="parkingList" 
            range-key="name"
            @change="onParkingChange"
          >
            <view class="picker-display">
              <text>{{ selectedParking.name || '请选择停车场' }}</text>
              <image class="icon-image-small" src="/static/icons/chevron-down.svg" mode="aspectFit" />
            </view>
          </picker>
        </view>
      </view>
      
      <view class="search-row">
        <view class="search-input">
          <input 
            v-model="searchBerthNo" 
            placeholder="输入泊位号查询" 
            @input="onSearchInput"
          />
          <image class="icon-image-small" src="/static/icons/search.svg" mode="aspectFit" />
        </view>
        <button class="refresh-btn" @click="refreshData">
          <image class="icon-image-medium" src="/static/icons/reload.svg" mode="aspectFit" />
        </button>
      </view>
    </view>

    <!-- 泊位网格展示 -->
    <view class="berth-grid-section">
      <scroll-view class="berth-scroll" scroll-y>
        <view class="berth-grid">
          <view 
            v-for="berth in filteredBerths" 
            :key="berth.id"
            class="berth-item"
            :class="getBerthClass(berth)"
            @click="onBerthClick(berth)"
          >
            <view class="berth-number">{{ berth.berthNo }}</view>
            <view class="berth-status">{{ getBerthStatusText(berth) }}</view>
            <view v-if="berth.plateNo" class="berth-plate">{{ berth.plateNo }}</view>
          </view>
        </view>
      </scroll-view>
    </view>

    <!-- 订单详情弹窗 -->
    <u-popup v-model="showOrderDetail" mode="bottom" height="60%">
      <view class="order-detail">
        <view class="detail-header">
          <text class="detail-title">订单详情</text>
          <image 
            class="icon-image" 
            src="/static/icons/x.svg" 
            mode="aspectFit" 
            @click="closeOrderDetail"
          />
        </view>
        
        <view v-if="selectedBerth" class="detail-content">
          <view class="detail-item">
            <text class="detail-label">泊位号:</text>
            <text class="detail-value">{{ selectedBerth.berthNo }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">车牌号:</text>
            <text class="detail-value">{{ selectedBerth.plateNo || '无' }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">泊位状态:</text>
            <text class="detail-value">{{ getBerthStatusText(selectedBerth) }}</text>
          </view>
          <view v-if="selectedBerth.orderInfo" class="order-info">
            <view class="detail-item">
              <text class="detail-label">订单号:</text>
              <text class="detail-value">{{ selectedBerth.orderInfo.orderNo }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">停车时间:</text>
              <text class="detail-value">{{ selectedBerth.orderInfo.startTime }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">订单状态:</text>
              <text class="detail-value">{{ selectedBerth.orderInfo.status }}</text>
            </view>
            <view class="detail-item">
              <text class="detail-label">费用:</text>
              <text class="detail-value">¥{{ selectedBerth.orderInfo.amount }}</text>
            </view>
          </view>
        </view>
      </view>
    </u-popup>
  </view>
</template>

<script>
export default {
  name: 'InspectionPage',
  data() {
    return {
      // 统计数据
      statsData: {
        totalBerths: 0,
        availableBerths: 0,
        disabledBerths: 0,
        registeredOrders: 0,
        unregisteredOrders: 0,
        manualOrders: 0
      },
      
      // 筛选数据
      areaList: [],
      selectedAreaIndex: 0,
      selectedArea: {},
      
      parkingList: [],
      selectedParkingIndex: 0,
      selectedParking: {},
      
      searchBerthNo: '',
      
      // 泊位数据
      berthList: [],
      filteredBerths: [],
      
      // 弹窗相关
      showOrderDetail: false,
      selectedBerth: null
    }
  },
  
  onLoad() {
    this.initData()
  },
  
  methods: {
    // 初始化数据
    async initData() {
      await this.loadAreas()
      await this.loadParkingLots()
      await this.loadBerthData()
      this.updateStats()
    },
    
    // 加载区域数据
    async loadAreas() {
      try {
        // 模拟数据，实际应调用API
        this.areaList = [
          { id: 1, name: '市中心区域' },
          { id: 2, name: '商业区域' },
          { id: 3, name: '住宅区域' }
        ]
        if (this.areaList.length > 0) {
          this.selectedArea = this.areaList[0]
        }
      } catch (error) {
        console.error('加载区域数据失败:', error)
      }
    },
    
    // 加载停车场数据
    async loadParkingLots() {
      try {
        // 模拟数据，实际应调用API
        this.parkingList = [
          { id: 1, name: '中央广场停车场', areaId: 1 },
          { id: 2, name: '商务大厦停车场', areaId: 1 },
          { id: 3, name: '购物中心停车场', areaId: 2 }
        ]
        if (this.parkingList.length > 0) {
          this.selectedParking = this.parkingList[0]
        }
      } catch (error) {
        console.error('加载停车场数据失败:', error)
      }
    },
    
    // 加载泊位数据
    async loadBerthData() {
      try {
        // 模拟数据，实际应调用API
        this.berthList = this.generateMockBerthData()
        this.filterBerths()
      } catch (error) {
        console.error('加载泊位数据失败:', error)
      }
    },
    
    // 生成模拟泊位数据
    generateMockBerthData() {
      const berths = []
      for (let i = 1; i <= 50; i++) {
        const berthNo = `A${i.toString().padStart(3, '0')}`
        const status = Math.random()
        let berthStatus, plateNo, orderInfo
        
        if (status < 0.3) {
          // 空闲
          berthStatus = 'available'
          plateNo = null
          orderInfo = null
        } else if (status < 0.6) {
          // 已停车
          berthStatus = 'occupied'
          plateNo = this.generatePlateNo()
          orderInfo = {
            orderNo: `ORD${Date.now()}${i}`,
            startTime: this.formatTime(new Date(Date.now() - Math.random() * 3600000)),
            status: Math.random() > 0.5 ? '已登记' : '未登记',
            amount: (Math.random() * 20 + 5).toFixed(2)
          }
        } else if (status < 0.8) {
          // 禁用
          berthStatus = 'disabled'
          plateNo = null
          orderInfo = null
        } else {
          // 人工取证
          berthStatus = 'manual'
          plateNo = this.generatePlateNo()
          orderInfo = {
            orderNo: `MAN${Date.now()}${i}`,
            startTime: this.formatTime(new Date(Date.now() - Math.random() * 1800000)),
            status: '人工取证',
            amount: (Math.random() * 30 + 10).toFixed(2)
          }
        }
        
        berths.push({
          id: i,
          berthNo,
          status: berthStatus,
          plateNo,
          orderInfo,
          parkingId: this.selectedParking.id
        })
      }
      return berths
    },
    
    // 生成随机车牌号
    generatePlateNo() {
      const provinces = ['京', '津', '沪', '渝', '冀', '豫', '云', '辽']
      const letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
      const numbers = '0123456789'
      
      let plateNo = provinces[Math.floor(Math.random() * provinces.length)]
      plateNo += letters[Math.floor(Math.random() * letters.length)]
      
      for (let i = 0; i < 5; i++) {
        if (Math.random() > 0.7) {
          plateNo += letters[Math.floor(Math.random() * letters.length)]
        } else {
          plateNo += numbers[Math.floor(Math.random() * numbers.length)]
        }
      }
      
      return plateNo
    },
    
    // 格式化时间
    formatTime(date) {
      const year = date.getFullYear()
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const hour = date.getHours().toString().padStart(2, '0')
      const minute = date.getMinutes().toString().padStart(2, '0')
      
      return `${year}-${month}-${day} ${hour}:${minute}`
    },
    
    // 更新统计数据
    updateStats() {
      const total = this.berthList.length
      const available = this.berthList.filter(b => b.status === 'available').length
      const disabled = this.berthList.filter(b => b.status === 'disabled').length
      const registered = this.berthList.filter(b => b.orderInfo && b.orderInfo.status === '已登记').length
      const unregistered = this.berthList.filter(b => b.orderInfo && b.orderInfo.status === '未登记').length
      const manual = this.berthList.filter(b => b.status === 'manual').length
      
      this.statsData = {
        totalBerths: total,
        availableBerths: available,
        disabledBerths: disabled,
        registeredOrders: registered,
        unregisteredOrders: unregistered,
        manualOrders: manual
      }
    },
    
    // 筛选泊位
    filterBerths() {
      let filtered = this.berthList
      
      // 根据停车场筛选
      if (this.selectedParking.id) {
        filtered = filtered.filter(berth => berth.parkingId === this.selectedParking.id)
      }
      
      // 根据泊位号搜索
      if (this.searchBerthNo.trim()) {
        filtered = filtered.filter(berth => 
          berth.berthNo.toLowerCase().includes(this.searchBerthNo.toLowerCase())
        )
      }
      
      this.filteredBerths = filtered
    },
    
    // 区域选择变化
    onAreaChange(e) {
      this.selectedAreaIndex = e.detail.value
      this.selectedArea = this.areaList[this.selectedAreaIndex]
      // 重新加载该区域的停车场
      this.loadParkingLots()
    },
    
    // 停车场选择变化
    onParkingChange(e) {
      this.selectedParkingIndex = e.detail.value
      this.selectedParking = this.parkingList[this.selectedParkingIndex]
      this.loadBerthData()
    },
    
    // 搜索输入
    onSearchInput() {
      this.filterBerths()
    },
    
    // 刷新数据
    refreshData() {
      this.loadBerthData()
    },
    
    // 泊位点击
    onBerthClick(berth) {
      this.selectedBerth = berth
      this.showOrderDetail = true
    },
    
    // 关闭订单详情
    closeOrderDetail() {
      this.showOrderDetail = false
      this.selectedBerth = null
    },
    
    // 获取泊位样式类
    getBerthClass(berth) {
      return {
        'berth-available': berth.status === 'available',
        'berth-occupied': berth.status === 'occupied',
        'berth-disabled': berth.status === 'disabled',
        'berth-manual': berth.status === 'manual'
      }
    },
    
    // 获取泊位状态文本
    getBerthStatusText(berth) {
      const statusMap = {
        'available': '空闲',
        'occupied': '已停车',
        'disabled': '禁用',
        'manual': '人工取证'
      }
      return statusMap[berth.status] || '未知'
    },
    
    // 返回上一页
    goBack() {
      uni.navigateBack()
    }
  }
}
</script>

<style scoped>
.inspection-page {
  min-height: 100vh;
  background-color: #f5f5f5;
}

/* 导航栏样式 */
.navbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 30rpx;
  background-color: #fff;
  border-bottom: 1px solid #eee;
}

.navbar-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
}

.navbar-right {
  width: 60rpx;
}

/* 图标样式 */
.icon-image {
  width: 48rpx;
  height: 48rpx;
  filter: brightness(0) saturate(100%) invert(20%) sepia(8%) saturate(1000%) hue-rotate(180deg);
}

.icon-image-small {
  width: 32rpx;
  height: 32rpx;
  filter: brightness(0) saturate(100%) invert(60%) sepia(8%) saturate(1000%) hue-rotate(180deg);
}

.icon-image-medium {
  width: 40rpx;
  height: 40rpx;
  filter: brightness(0) saturate(100%) invert(40%) sepia(8%) saturate(1000%) hue-rotate(180deg);
}

/* 统计数据区域 */
.stats-section {
  padding: 30rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 30rpx;
}

.stat-item {
  text-align: center;
  padding: 20rpx;
  background-color: #f8f9fa;
  border-radius: 12rpx;
}

.stat-value {
  display: block;
  font-size: 48rpx;
  font-weight: 600;
  color: #2c5aa0;
  margin-bottom: 10rpx;
}

.stat-label {
  font-size: 24rpx;
  color: #666;
}

/* 筛选区域 */
.filter-section {
  padding: 30rpx;
  background-color: #fff;
  margin-bottom: 20rpx;
}

.filter-row {
  display: flex;
  gap: 30rpx;
  margin-bottom: 30rpx;
}

.filter-item {
  flex: 1;
}

.filter-label {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 10rpx;
  display: block;
}

.picker-display {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx;
  background-color: #f8f9fa;
  border-radius: 8rpx;
  border: 1px solid #ddd;
}

.search-row {
  display: flex;
  gap: 20rpx;
  align-items: center;
}

.search-input {
  flex: 1;
  position: relative;
}

.search-input input {
  width: 100%;
  padding: 20rpx 60rpx 20rpx 20rpx;
  background-color: #f8f9fa;
  border: 1px solid #ddd;
  border-radius: 8rpx;
  font-size: 28rpx;
}

.search-input .icon-image-small {
  position: absolute;
  right: 20rpx;
  top: 50%;
  transform: translateY(-50%);
}

.refresh-btn {
  padding: 20rpx;
  background-color: #2c5aa0;
  border: none;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.refresh-btn .icon-image-medium {
  filter: brightness(0) saturate(100%) invert(100%);
}

/* 泊位网格区域 */
.berth-grid-section {
  flex: 1;
  padding: 0 30rpx;
}

.berth-scroll {
  height: calc(100vh - 600rpx);
}

.berth-grid {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 20rpx;
  padding-bottom: 30rpx;
}

.berth-item {
  aspect-ratio: 1;
  padding: 20rpx;
  border-radius: 12rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  text-align: center;
  border: 2px solid transparent;
  transition: all 0.3s ease;
}

.berth-item:active {
  transform: scale(0.95);
}

.berth-available {
  background-color: #d4edda;
  border-color: #28a745;
}

.berth-occupied {
  background-color: #f8d7da;
  border-color: #dc3545;
}

.berth-disabled {
  background-color: #e2e3e5;
  border-color: #6c757d;
}

.berth-manual {
  background-color: #fff3cd;
  border-color: #ffc107;
}

.berth-number {
  font-size: 24rpx;
  font-weight: 600;
  color: #333;
  margin-bottom: 8rpx;
}

.berth-status {
  font-size: 20rpx;
  color: #666;
  margin-bottom: 8rpx;
}

.berth-plate {
  font-size: 18rpx;
  color: #333;
  background-color: rgba(255, 255, 255, 0.8);
  padding: 4rpx 8rpx;
  border-radius: 4rpx;
  max-width: 100%;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 订单详情弹窗 */
.order-detail {
  padding: 40rpx;
  background-color: #fff;
  border-radius: 20rpx 20rpx 0 0;
}

.detail-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 40rpx;
  padding-bottom: 20rpx;
  border-bottom: 1px solid #eee;
}

.detail-title {
  font-size: 36rpx;
  font-weight: 600;
  color: #333;
}

.detail-content {
  max-height: 60vh;
  overflow-y: auto;
}

.detail-item {
  display: flex;
  align-items: center;
  padding: 20rpx 0;
  border-bottom: 1px solid #f5f5f5;
}

.detail-label {
  width: 200rpx;
  font-size: 28rpx;
  color: #666;
  flex-shrink: 0;
}

.detail-value {
  flex: 1;
  font-size: 28rpx;
  color: #333;
  text-align: right;
}

.order-info {
  margin-top: 30rpx;
  padding-top: 30rpx;
  border-top: 2px solid #f0f0f0;
}

/* 深色模式适配 */
@media (prefers-color-scheme: dark) {
  .inspection-page {
    background-color: #1a1a1a;
  }
  
  .navbar,
  .stats-section,
  .filter-section,
  .order-detail {
    background-color: #2d2d2d;
    border-color: #404040;
  }
  
  .navbar-title,
  .stat-value,
  .detail-title,
  .detail-value,
  .berth-number {
    color: #fff;
  }
  
  .stat-label,
  .filter-label,
  .detail-label,
  .berth-status {
    color: #ccc;
  }
  
  .stat-item,
  .picker-display,
  .search-input input {
    background-color: #404040;
    border-color: #555;
    color: #fff;
  }
  
  .icon-image {
    filter: brightness(0) saturate(100%) invert(80%);
  }
  
  .icon-image-small,
  .icon-image-medium {
    filter: brightness(0) saturate(100%) invert(70%);
  }
}
</style>